import requests
import base64
import time
import json
import datetime
from urllib import parse


###############################################

# date = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
date = "2025-01-02"
doctorName = "普通号" ######## 霍炳杰
sectionId = "A070207" # "ZA070203"# 中医疑难病门诊 # A0709 本部 中医科门诊
departmentName = "中西医结合肿瘤门诊"
headers = {
    "Host": "311005.jiankanghebei.cn",
    "timestamp": str(int(time.time() * 1000)),
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090b13) XWEB/9185 Flue",
    "Accept": "application/json, text/javascript, */*; q=0.01",
    # "sign": b64encode("BeginDate=2024-08-21&EndDate=2024-08-21&doctorId=&hospitalBranchCode=0&hospitalId=311005&sectionId=A0709"),
    "Cookie": "SESSION=fd753042-9972-4be1-9a8c-7cf62a328a87",
    "Origin": "https://311005.jiankanghebei.cn",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Reffer": "https://311005.jiankanghebei.cn/ShengSiInternetHospital/fronthtml/appoint/choose_doctor.jsp"
}
userId = "10777238"
PatientName = "宋亚斌"
identityCardNum = "132331198007222852"
Sex = "男"
weChatStr = "oTijfjqfU9hLG-YRRVG6ahYPoUSQ"
###############################################


sess = requests.Session()
proxies = {
    "http": "", "https": ""
}


def b64encode(s):
    return base64.b64encode(s.encode('utf-8')).decode('utf-8')


def signData(data: dict):
    data.pop("sign")
    keys = sorted(data.keys())
    msg = ""
    for k in keys:
        msg += k + "=" + parse.quote(parse.quote(str(data[k]))) + "&"
    msg = msg[:-1]
    data["sign"] = b64encode(msg)


def dataDecode(res):
    r = json.loads(res.json())
    if len(r.get("data").strip()) == 0:
        return r.get("data").strip()
    return json.loads(r.get("data").strip())


def GetRegDateInfo():
    """
    获取当日的医生信息
    :return:
    """
    url = "https://311005.jiankanghebei.cn/ShengSiInternetHospital/AppointController/getRegDateInfo.do"
    data = {
        "hospitalId": "311005",
        # "sectionId": "A0709",
        "sectionId": sectionId,
        "doctorId": "",
        "hospitalBranchCode": "0",
        "BeginDate": date,
        "EndDate": date,
        "sign": b64encode("BeginDate={}&EndDate={}&doctorId=&hospitalBranchCode=0&hospitalId=311005&sectionId=A0709".format(date, date))
    }
    signData(data)
    res = sess.post(url, data=data, proxies=proxies, headers=headers)
    # print(json.dumps(json.loads(json.loads(res.json()).get('data')), indent=4, ensure_ascii=False))
    s = json.loads(res.json())
    if s.get("code") != "0":
        print(s)
        return None
    doctorList = json.loads(json.loads(res.json()).get('data'))
    if len(doctorList) > 0:
        for doctor in doctorList:
            if doctor.get("DoctorName") == doctorName:
                print(json.dumps(doctor, ensure_ascii=False, indent=4))
                return doctor
    return None


def getRegisterListByDoctorId(doctorid="1441_霍炳杰"):
    """
    获取指定日期的号
    :return:
    """
    url = "https://311005.jiankanghebei.cn/ShengSiInternetHospital/DayRegisterController/getRegisterListByDoctorId.do"
    data = {
        "hospitalCode": "311005",
        "SectionId": "A0709",
        "DoctorId": doctorid,
        # "DoctorId": "2316_石文成",
        "hospitalBranchCode": "0",
        # "BeginDate": "2024-08-21",
        # "EndDate": "2024-08-21",
        # "isAmOrPm":	"",
        "sign": b64encode(
            "DoctorId={}&SectionId=A0709&hospitalBranchCode=0&hospitalCode=311005".format(parse.quote(parse.quote(doctorid))))
    }
    signData(data)
    res = sess.post(url, data=data, proxies=proxies, headers=headers)
    data = dataDecode(res)
    if len(data) == 0:
        print("没有号源")
    else:
        print(json.dumps(data, indent=4, ensure_ascii=False), datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        if date in data:
            infoList = data[date]
            for info in infoList:
                remainNum = info.get("remainNum")
                if remainNum > "0":
                    return info
    return None
    # {
    #     "2024-08-15": [
    #         {
    #             "SequenceNo": "",
    #             "remainNum": "1",
    #             "week": "星期四",
    #             "IdNumberFromHospital": "",
    #             "PayFee": "0",
    #             "SequenceNum": "7702108663|14:21|14:42|0|A0709|石文成|2024-08-15",
    #             "sourceDate": "2024-08-15",
    #             "TotalCost": "0",
    #             "DoctorId": "2316_石文成",
    #             "ServiceFee": "",
    #             "TotalNum": "1",
    #             "startTime": "14:21",
    #             "endTime": "14:42",
    #             "AmOrPm": "pm",
    #             "OtherFee": "0"
    #         },
    #         {
    #             "SequenceNo": "",
    #             "remainNum": "1",
    #             "week": "星期四",
    #             "IdNumberFromHospital": "",
    #             "PayFee": "0",
    #             "SequenceNum": "7702108668|16:06|16:27|0|A0709|石文成|2024-08-15",
    #             "sourceDate": "2024-08-15",
    #             "TotalCost": "0",
    #             "DoctorId": "2316_石文成",
    #             "ServiceFee": "",
    #             "TotalNum": "1",
    #             "startTime": "16:06",
    #             "endTime": "16:27",
    #             "AmOrPm": "pm",
    #             "OtherFee": "0"
    #         },
    #         {
    #             "SequenceNo": "",
    #             "remainNum": "1",
    #             "week": "星期四",
    #             "IdNumberFromHospital": "",
    #             "PayFee": "0",
    #             "SequenceNum": "7702108669|16:27|16:48|0|A0709|石文成|2024-08-15",
    #             "sourceDate": "2024-08-15",
    #             "TotalCost": "0",
    #             "DoctorId": "2316_石文成",
    #             "ServiceFee": "",
    #             "TotalNum": "1",
    #             "startTime": "16:27",
    #             "endTime": "16:48",
    #             "AmOrPm": "pm",
    #             "OtherFee": "0"
    #         },
    #         {
    #             "SequenceNo": "",
    #             "remainNum": "1",
    #             "week": "星期四",
    #             "IdNumberFromHospital": "",
    #             "PayFee": "0",
    #             "SequenceNum": "7702108670|16:48|17:09|0|A0709|石文成|2024-08-15",
    #             "sourceDate": "2024-08-15",
    #             "TotalCost": "0",
    #             "DoctorId": "2316_石文成",
    #             "ServiceFee": "",
    #             "TotalNum": "1",
    #             "startTime": "16:48",
    #             "endTime": "17:09",
    #             "AmOrPm": "pm",
    #             "OtherFee": "0"
    #         },
    #         {
    #             "SequenceNo": "",
    #             "remainNum": "1",
    #             "week": "星期四",
    #             "IdNumberFromHospital": "",
    #             "PayFee": "0",
    #             "SequenceNum": "7702108671|17:09|17:30|0|A0709|石文成|2024-08-15",
    #             "sourceDate": "2024-08-15",
    #             "TotalCost": "0",
    #             "DoctorId": "2316_石文成",
    #             "ServiceFee": "",
    #             "TotalNum": "1",
    #             "startTime": "17:09",
    #             "endTime": "17:30",
    #             "AmOrPm": "pm",
    #             "OtherFee": "0"
    #         }
    #     ]
    # }
    # print(res.textdataDecode(res))
    # print(json.dumps(dataDecode(res), indent=4, ensure_ascii=False))


def getPatientCardByuserId():
    """
    获取已经添加的就诊卡信息
    :return:
    """
    url = "https://311005.jiankanghebei.cn/ShengSiInternetHospital/PatientController/getPatientCardByuserId.do"
    data = {
        "userId": userId,
        "hospitalCode": "311005",
        "isDatabase": "false",
        "isDefault": "false",
        "sign": b64encode("hospitalCode=311005&isDatabase=false&isDefault=false&userId={}".format(userId))
    }
    res = sess.post(url, data=data, proxies=proxies, headers=headers)
    data = dataDecode(res)
    for k in data.keys():
        if identityCardNum in k:
            return [k, data.get(k)]
    print(json.dumps(data, indent=4, ensure_ascii=False))
    return None
    """
    {
        "牛少波,11466278,17733863156,130126199402160330,false,true,2,success,30": [
            {
                "CardNo": "A122048045",
                "HisIdExp": "tc/DuWTw2Mr6ofAuc/Yupg==",
                "HisId": "A122048045",
                "CardType": "就诊卡",
                "IsMedicarePatient": ""
            }
        ],
        "宋亚斌,11533869,17712345678,132331198007222852,true,true,2,success,44": [
            {
                "CardNo": "A122092523",
                "HisIdExp": "jzCpUAQvmAysu+cn+cMWQw==",
                "HisId": "A122092523",
                "CardType": "就诊卡",
                "IsMedicarePatient": ""
            }
        ]
    }
    """


def addRegister(DepartmentId="A0709", SequenceNum="7702052113|17:09|17:30|0|A0709|石文成|2024-08-09", DoctorHisId="2316_石文成",
                Date="2024-08-09", BeginTime="17:09", EndTime="17:30", DoctorName="石文成", DepartmentName="中医科门诊",
                PatientHisId="11533869", PatientName="宋亚斌", PhoneNum="17712345678",
                identityCardNum="132331198007222852", Sex="男", CardNum="A122092523",
                userId="10777238",
                weChatStr="oTijfjqfU9hLG-YRRVG6ahYPoUSQ"):
    """
    挂号
    :return:
    """

    url = "https://311005.jiankanghebei.cn/ShengSiInternetHospital/DayRegisterController/addRegister.do"
    data = {
        "hospitalCode": "311005",
        "DoctorType": "0",
        "PayFee": "0.00",
        "SequenceNum": SequenceNum,
        "DepartmentId": DepartmentId,
        "DoctorHisId": DoctorHisId,
        "PatientHisId": PatientHisId,
        "PatientName": PatientName,
        "PhoneNum": PhoneNum,
        "identityCardNum": identityCardNum,
        "Sex": Sex,
        "CardNum": CardNum,
        "CardType": "就诊卡",
        "Date": Date,
        "BeginTime": BeginTime,
        "EndTime": EndTime,
        "HospitalId": "0",
        "DoctorName": DoctorName,
        "DepartmentName": DepartmentName,
        "userId": userId,
        "weChatStr": weChatStr
    }
    signData(data)
    res = sess.post(url, data=data, proxies=proxies, headers=headers)
    data = dataDecode(res)
    print(json.dumps(data, indent=4, ensure_ascii=False))


for i in range(1000):
    doctor = GetRegDateInfo()
    if doctor:
        print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        regdata = getRegisterListByDoctorId(doctor.get("DoctorId"))
        if regdata:
            card = getPatientCardByuserId()
            if card:
                addRegister(DepartmentId=sectionId, SequenceNum=regdata.get("SequenceNum"),
                            DoctorHisId=regdata.get("DoctorId"), Date=regdata.get("sourceDate"),
                            BeginTime=regdata.get("BeginTime"), EndTime=regdata.get("EndTime"),
                            DoctorName=doctorName, DepartmentName=departmentName,
                            PatientHisId=card[0].split(",")[1], PatientName=card[0].split(",")[0],
                            PhoneNum=card[0].split(",")[2], identityCardNum=card[0].split(",")[3],
                            Sex=Sex, CardNum=card[1][0].get("CardNo"), userId=userId,
                            weChatStr=weChatStr
                            )
            print(card)
        break
    print(i)
    time.sleep(1)
